﻿using System.Collections;
using System.Collections.Immutable;
using System.Diagnostics;
using DimensionsHelper.LanguageService.Symbols;
using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService;

public class AnalysisBlock : AnalysisStatement, IEnumerable<AnalysisStatement>
{
    internal AnalysisBlock(Block syntaxNode, AnalysisNode? parent) : base(AnalysisBoundKinds.Block, syntaxNode, parent)
    {
        Syntax = syntaxNode;
    }


    private readonly List<AnalysisStatement> _children = [];

    public override Block Syntax { get; }


    public override int ChildrenCount => _children.Count;


    public IEnumerator<AnalysisStatement> GetEnumerator()
    {
        foreach (AnalysisNode? node in GetChildren())
        {
            if (node is AnalysisStatement analysisStatement)
            {
                yield return analysisStatement;
            }
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }


    public override IEnumerable<AnalysisNode> GetChildren()
    {
        return _children.ToImmutableArray();
    }

    internal override void AddChild(AnalysisNode child)
    {
        // 跳过空语句
        if (child.BoundKind == AnalysisBoundKinds.EmptyStatement)
        {
            return;
        }

        Debug.Assert(child.IsStatement);

        child.Parent = this;
        _children.Add((AnalysisStatement)child);
    }
}

public static partial class AnalysisNodeFactory
{
    /// <summary>
    /// 创建一个语句块
    /// </summary>
    /// <param name="syntaxNode">原始语法节点</param>
    /// <param name="parent">父节点，可以忽略</param>
    /// <param name="withSymbol">语法节点所在的With语句上下文类型符号</param>
    public static AnalysisBlock Block(Block syntaxNode, AnalysisNode? parent, ITypeSymbol? withSymbol)
    {
        return new AnalysisBlock(syntaxNode, parent).WithContainingWithSymbol(withSymbol);
    }
}